//
//  PaymentController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/14.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit


class PaymentController: UIViewController {
    
    private var coverView: UIView = { //遮罩
        let view = UIView()
        view.isUserInteractionEnabled = true
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    /***passwordPanel区域***/
    private var passwordPanel: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.isHidden = true
        view.layer.cornerRadius = 8
        return view
    }()
    
    private var panelTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "请输入太公民工交易密码，验证身份"
        label.font = wwFont_Regular(13)
        return label
    }()
    
    private var closeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage.init(named: "Icon_关闭")!.withRenderingMode(.alwaysTemplate), for: .normal)
        button.imageView?.tintColor = colorWithRGB(r: 252, g: 78, b: 59)
        return button
    }()
    
    private var separatorLine: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.mg_lightGray
        return view
    }()
    
    //提现金额
    private var moneyTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "提现金额"
        label.font = wwFont_Regular(12)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
    //金额
    var moneyDetailLabel: UILabel = {
        let label = UILabel()
        label.font = wwFont_Medium(26)
        label.text = "￥600.0"
        return label
    }()
    
    let passwordInputView = PasswordInputView()

    var inputPasswordCompletion:((String) -> Void)?
    
    //panel在y轴的中心位置
    private var panelCenterY: CGFloat = 0
    
    init() {
        super.init(nibName: nil, bundle: nil)
        
        self.transitioningDelegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.sharedManager().enableAutoToolbar = false//取消键盘上的toolBar
        IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = false//取消点击背景隐藏键盘的功能
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
        IQKeyboardManager.sharedManager().enableAutoToolbar = true
        IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
        self.closeButton.addTarget(self, action: #selector(doCloseButtonAction), for: .touchUpInside)

        self.setupViews()
        self.passwordInputView.setFirstResponder = true
        self.passwordInputView.passwordInputHandler = {[unowned self](password) in
            if password.count == 6 {
                if let closure = self.inputPasswordCompletion {
                    closure(password)
                }
                self.dismiss(animated: true, completion: nil)
            }
        }
    }

    func setupViews() {
        
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        /***密码区域***/
        self.view.addSubview(self.passwordPanel)
        self.passwordPanel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.centerY.equalTo(self.panelCenterY)
            //make.top.equalTo(100)
            make.left.equalTo(self.view).offset(20)
            make.right.equalTo(self.view).offset(-20)
            make.height.equalTo(200)
        }
        
        self.passwordPanel.addSubview(self.panelTitleLabel)
        self.panelTitleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.passwordPanel).offset(8)
            make.left.equalTo(self.passwordPanel).offset(20)
            make.height.equalTo(30)
        }
        
        
        self.passwordPanel.addSubview(self.closeButton)
        self.closeButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(self.panelTitleLabel).offset(-7)
            make.right.equalTo(self.passwordPanel).offset(-10)
            make.width.height.equalTo(20)
        }
        
        self.passwordPanel.addSubview(self.separatorLine)
        self.separatorLine.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.passwordPanel)
            make.top.equalTo(self.panelTitleLabel.snp.bottom).offset(8)
            make.height.equalTo(1)
        }
        
        self.passwordPanel.addSubview(self.moneyTitleLabel)
        self.moneyTitleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.separatorLine.snp.bottom).offset(5)
            make.centerX.equalTo(self.passwordPanel)
            make.height.equalTo(20)
        }
        
       self.passwordPanel.addSubview(self.moneyDetailLabel)
       self.moneyDetailLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.passwordPanel)
            make.top.equalTo(self.moneyTitleLabel.snp.bottom).offset(5)
            make.height.equalTo(40)
        }
        
      self.passwordPanel.addSubview(self.passwordInputView)
      self.passwordInputView.snp.makeConstraints { (make) in
        make.left.equalTo(self.passwordPanel).offset(20)
        make.right.equalTo(self.passwordPanel).offset(-20)
   make.top.equalTo(self.moneyDetailLabel.snp.bottom).offset(10)
            make.height.equalTo(50)
        }
    }
    
    @objc func keyboardDidShow(_ notification: Notification) {
        
        //有个问题，获取passwordPanel的中心位置需要提前知道键盘高度，然后要获取键盘高度需要先把passwordPanel添加到视图。。。。所以一开始passwordPanel是隐藏的，当获取到键盘高度后，设置中心位置，然后再显示出来。
        
        guard let keyboardInfo = notification.userInfo else {
            return
        }
        
        if let keyboardBound = keyboardInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect {
            let keyboardHeight = keyboardBound.height
            self.panelCenterY = (self.view.bounds.height - keyboardHeight)/2
            
            self.passwordPanel.isHidden = false
           self.passwordPanel.snp.updateConstraints({ (make) in
                make.centerY.equalTo(self.panelCenterY)
            })
        }
    }
    
    @objc func doCloseButtonAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

//跳转动画
extension PaymentController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return PaymentControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return PaymentControllerTransitionDismiss()
    }
}

class PaymentControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 1
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from)!//A controller
        let toVc = transitionContext.viewController(forKey: .to)!//B controller
        
        
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        toVc.view.alpha = 0
        UIView.animate(withDuration: 1, animations: {
            toVc.view.alpha = 1
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromVc.view)
            toVc.view.sendSubview(toBack: fromVc.view)
        }
    }
}

class PaymentControllerTransitionDismiss: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 1
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        //        let fromView = transitionContext.view(forKey: .from)!
        let toView = transitionContext.view(forKey: .to)!
        
        let container = transitionContext.containerView
        container.addSubview(toView)
        
        UIView.animate(withDuration: 0.3, animations: {
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
